<?php
// +----------------------------------------------------------------------
// | sfadmin - Suifeng Administration
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2020 http://suifeng.tech All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: suifeng <1787585212@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\common;

use app\admin\common\Pagination;

final class AdminList
{
    // 分页显示定制
    public $config = array(
        'header' => '<span class="rows">共 %TOTAL_ROW% 条记录</span>',
        'prev'   => '上一页',
        'next'   => '下一页',
        'first'  => '首页',
        'last'   => '末页',
        'theme'  => '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%',
        'info'   => '总共 %TOTAL% 条记录，显示第 %START% 到 %END% 条',
    );

    // 分页栏每页显示的页数
    public $roll_page = 7;

    // 下列属性可以从request获取。
    public $page_url;
    public $page_num;
    public $page_size;
    public $sort_field;
    public $sort_order;
    public $search_word;
    public $selected;
    public $where_map;
    public $input_data;

    // 下列属性需要外部设置。
    public $page_count;
    public $total_rows;
    public $data_list = array();
    public $controller;

    public function __construct($controller)
    {
        $this->controller = $controller;
        $this->page_num = input('page', 1);
        $this->page_size = input('size', config('ADMIN_PAGE_ROWS'));
        $this->sort_field = input('sort', '');
        $this->sort_order = input('order', '');
        $this->search_word = input('search', '');
        $this->selected = (array) input('ids/a');

        $this->where_map = array();
        $this->input_data = request()->param();

        foreach (array_keys($this->input_data) as $key) {
            if (substr($key, 0, 2) == 'q_') {
                $this->where_map[substr($key, 2)] = $this->input_data[$key];
            }
        }

        $this->page_url = $this->controller->url(request()->action(), ['page' => '[PAGE]']);
    }


    // --------------------------------------------------------------------
    // 下面是分页有关的方法。
    // --------------------------------------------------------------------

    public function show_pages()
    {
        if (0 == $this->total_rows || $this->total_rows <= $this->page_size) {
            return '';
        }

        // 如果没有设置page_url，则自动生成
        if (empty($this->page_url)) {
            $parameter[$this->pageVar] = '[PAGE]';
            $this->page_url = url(request()->action(), $parameter);
        }

        /* 计算分页信息 */
        $totalPages = ceil($this->total_rows / $this->page_size); //总页数
        if (!empty($totalPages) && $this->page_num > $totalPages) {
            $this->page_num = $totalPages;
        }

        /* 计算分页临时变量 */
        $now_cool_page = $this->roll_page / 2;
        $now_cool_page_ceil = ceil($now_cool_page);

        //上一页
        $up_row  = $this->page_num - 1;
        //$up_page = $up_row > 0 ? '<li><a class="prev" href="' . $this->page_url($up_row) . '">' . $this->config['prev'] . '</a></li>' : '';
        $up_page = $this->page($up_row > 0 ? $up_row : null, $this->config['prev'], 'prev', $up_row > 0);

        //下一页
        $down_row  = $this->page_num + 1;
        //$down_page = ($down_row <= $totalPages) ? '<li><a class="next" href="' . $this->page_url($down_row) . '">' . $this->config['next'] . '</a></li>' : '';
        $down_page = $this->page($down_row <= $totalPages ? $down_row : null, $this->config['next'], 'prev', $down_row <= $totalPages);

        //第一页
        $the_first = '';
        if ($totalPages > $this->roll_page && ($this->page_num - $now_cool_page) >= 1) {
            $the_first = '<li><a class="first" href="' . $this->page_url(1) . '">' . $this->config['first'] . '</a></li>';
        } else if ($totalPages > 10) {
            $the_first = $this->page(null, $this->config['first'], 'first', false);
        }

        //最后一页
        $the_end = '';
        if ($totalPages > $this->roll_page && ($this->page_num + $now_cool_page) < $totalPages) {
            $the_end = '<li><a class="end" href="' . $this->page_url($totalPages) . '">' . $this->config['last'] . '</a></li>';
        } else if ($totalPages > 10) {
            $the_end = $this->page(null, $this->config['last'], 'last', false);
        }

        //数字连接
        $link_page = "";
        for ($i = 1; $i <= $this->roll_page; $i++) {
            if (($this->page_num - $now_cool_page) <= 0) {
                $page = $i;
            } elseif (($this->page_num + $now_cool_page - 1) >= $totalPages) {
                $page = $totalPages - $this->roll_page + $i;
            } else {
                $page = $this->page_num - $now_cool_page_ceil + $i;
            }
            if ($page > 0 && $page != $this->page_num) {

                if ($page <= $totalPages) {
                    $link_page .= $this->page($page, $page, 'num', true);
                } else {
                    break;
                }
            } else {
                if ($page > 0 && 1 != $totalPages) {
                    $link_page .= $this->page($page, $page, 'num active', true);
                }
            }
        }

        if ($link_page) {
            //if (!$up_page) {
            //    $up_page = '<li><a class="prev" href="#">没有了</a></li>';
            //}
            if (!$down_page) {
                $down_page = '<li><a class="next" href="#">没有了</a></li>';
            }
        }

        //替换分页内容
        $page_str = str_replace(
            array('%HEADER%', '%NOW_PAGE%', '%UP_PAGE%', '%DOWN_PAGE%', '%FIRST%', '%LINK_PAGE%', '%END%', '%TOTAL_ROW%', '%TOTAL_PAGE%'),
            array($this->config['header'], $this->page_num, $up_page, $down_page, $the_first, $link_page, $the_end, $this->total_rows, $totalPages),
            $this->config['theme']);
        return "{$page_str}";
    }

    public function show_info()
    {
        if (0 == $this->total_rows) {
            return '';
        }

        $start = ($this->page_num - 1) * $this->page_size + 1;
        $end = $start + $this->page_size - 1 < $this->total_rows ? $start + $this->page_size - 1: $this->total_rows;

        return str_replace(
            array('%START%', '%END%', '%TOTAL%'),
            array($start, $end, $this->total_rows),
            $this->config['info']);
    }

    private function page($page, $text, $class, $enable)
    {
        if ($enable) {
            return '<li class="' . $class . '"><a href="' . $this->url($page) . '">' . $text . '</a></li>';
        } else {
            return '<li class="' . $class . '"><span>' . $text . '</span></li>';
        }
    }

    private function url($page)
    {
        return str_replace(urlencode('[page]'), $page, $this->page_url);
    }


    // --------------------------------------------------------------------
    // 下面是表格有关的方法。
    // --------------------------------------------------------------------

    public function render_search_box()
    {
        $input_html = helper('admin/html')->render_tag('input', array('type' => 'text', 'name'=> 'search', 'value' => $this->search_word, 'placeholder' => '搜索', 'class' => 'search-input form-control'));
        $span_html = helper('admin/html')->render_icon('fa fa-search');
        $span_html = helper('admin/html')->render_tag('a', array('class' => 'btn btn-default search-btn form-get'), $span_html);
        $span_html = helper('admin/html')->render_tag('span', array('class' => 'input-group-btn'), $span_html);

        $html = helper('admin/html')->render_tag('div', array('class' => 'input-group search-box'), $input_html . $span_html);
        $html = helper('admin/html')->render_tag('div', array('class' => 'form-group'), $html);
        return $html;
    }

    public function render_header_select($options = array())
    {
        $attributes['type'] = 'checkbox';
        $attributes['class'] = 'check-all';
        $attributes = array_merge($attributes, $options);
        return helper('admin/html')->render_tag('input', $attributes);
    }

    public function render_header_text($text, $options = array())
    {
        if (empty($options)) {
            return $text;
        }

        $attributes = $options;
        return helper('admin/html')->render_tag('span', $attributes, $text);
    }

    public function render_column_select($value, $options = array())
    {
        $attributes['type'] = 'checkbox';
        $attributes['class'] = 'ids';
        $attributes['name'] = 'ids[]';
        $attributes['value'] = $value;
        in_array($value, $this->selected) && $attributes['checked'] = 'checked';
        $attributes = array_merge($attributes, $options);
        return helper('admin/html')->render_tag('input', $attributes);
    }

    public function render_column_text($value, $options = array())
    {
        if (isset($options['list'])) {
            $list = (array) $options['list'];
            unset($options['list']);
        } else {
            $list = array();
        }

        if (isset($options['link'])) {
            $link = $options['link'];
            unset($options['link']);
        } else {
            $link = '';
        }

        if (isset($options['format'])) {
            $format = $options['format'];
            unset($options['format']);

            if ($value) {
                $value = helper('common/format')->$format($value);
            }
        }

        if ($list) {
            if (array_key_exists($value, $list)) {
                $display = $list[$value];

                if (is_array($display)) {
                    $text = array_shift($display);
                    $class = array_shift($display);

                    $attributes = $options;
                    $attributes['class'] = $class;
                    $display = helper('admin/html')->render_tag('span', $attributes, $text);
                }
            } else {
                $display = '';
            }
        } else {
            $display = htmlspecialchars($value);
        }

        if ($link) {
            $attributes = $options;
            $attributes['href'] = $link;
            $display = helper('admin/html')->render_tag('a', $attributes, $display);
        }

        return $display;
    }

    public function render_column_url($value, $options = array())
    {
        if ($value) {
            $attributes['href'] = $value;
            $attributes['class'] = 'url';
            $attributes['target'] = '_blank';
            $attributes = array_merge($attributes, $options);
            return helper('admin/html')->render_tag('a', $attributes, $value);
        } else {
            return '';
        }
    }

    public function render_column_status($value, $options = array())
    {
        $options['list'] = array(
            0 => array('无效', 'label label-danger'),
            1 => array('有效', 'label label-success'),
        );
        return $this->render_column_text($value, $options);
    }

    public function render_column_image($value, $options = array())
    {
        $url = model('admin/upload')->get_url($value);
        if ($url) {
            $attributes['src'] = $url;
            $attributes['class'] = 'thumb';
            $attributes = array_merge($attributes, $options);
            return helper('admin/html')->render_tag('img', $attributes);
        } else {
            return '';
        }
    }

    public function render_column_date($value, $options = array())
    {
        if ($value) {
            $display = helper('admin/format')->date($value);
            $attributes['class'] = 'date_ts';
            $attributes = array_merge($attributes, $options);
            return helper('admin/html')->render_tag('span', $attributes, $display);
        } else {
            return '';
        }
    }

    public function render_column_date_time($value, $options = array())
    {
        if ($value) {
            $display = helper('admin/format')->date_time($value);
            $attributes['class'] = 'date_ts';
            $attributes = array_merge($attributes, $options);
            return helper('admin/html')->render_tag('span', $attributes, $display);
        } else {
            return '';
        }
    }

    public function render_action($text, $icon, $class, $options = array())
    {
        $icon_html = $icon ? helper('admin/html')->render_tag('i', array('class' => $icon)) : null;

        $attributes['type'] = 'button';
        $attributes['class'] = $class;
        $attributes['title'] = $text;
        $attributes = array_merge($attributes, $options);
        return helper('admin/html')->render_tag('button', $attributes, $icon_html);
    }

    public function render_empty_row($options = array())
    {
        $html = '';
        $html .= helper('admin/html')->render_start_tag('tr', array('class' => 'data-empty'));
        $html .= helper('admin/html')->render_start_tag('td', array('class' => 'text-center empty-info', 'colspan' => '50'));
        $html .= helper('admin/html')->render_tag('i', array('class' => 'fa fa-database'));
        $html .= helper('admin/html')->render_tag('span', null, '暂时没有数据');
        $html .= helper('admin/html')->render_end_tag('td');
        $html .= helper('admin/html')->render_end_tag('tr');
        return $html;
    }

    public function render_pagination($page_url = null)
    {
        if ($page_url) {
            $this->page_url = $page_url;
        }

        if (empty($this->list_data)) {
            return;
        }

        $html = '';
        $html .= helper('admin/html')->render_start_tag('div', array('class' => 'row'));

        $html .= helper('admin/html')->render_start_tag('div', array('class' => 'col-sm-5'));
        $html .= helper('admin/html')->render_start_tag('div', array('class' => 'pagination-info'));
        $html .= $this->show_info();
        $html .= helper('admin/html')->render_end_tag('div');
        $html .= helper('admin/html')->render_end_tag('div');

        $html .= helper('admin/html')->render_start_tag('div', array('class' => 'col-sm-7'));
        $html .= helper('admin/html')->render_start_tag('ul', array('class' => 'pagination'));
        $html .= $this->show_pages();
        $html .= helper('admin/html')->render_end_tag('ul');
        $html .= helper('admin/html')->render_end_tag('div');

        $html .= helper('admin/html')->render_end_tag('div');
        return $html;
    }
}